//
//  M4CrediteInfoViewController.swift
//  M4
//
//  Created by jie on 2025/3/4.
//

import UIKit
import KakaJSON

class M4CrediteInfoViewController: M4BaseViewController {
    
    private var m4educationData: [M4InfoItemListModel] = []
    private var m4marryData: [M4InfoItemListModel] = []
    private var m4workData: [M4InfoItemListModel] = []
    private var m4incomeData: [M4InfoItemListModel] = []
    private var m4relationshipData: [M4InfoItemListModel] = []
    private var titles = [
        "¿Ha solicitado préstamos en línea antes? Si no, seleccione 0. Si sí, indique la cantidad de préstamos.",
        "¿Cuántas cuentas personales de préstamos vigentes tiene?",
        "¿Cuál es el monto total aproximado de las cuentas  personales de préstamos pendientes de pago?",
        "¿Ha tenido cuentas impagas o vencidas en los últimos seis meses?",
        "¿Cuántos días fue la demora máxima en el pago durante los últimos seis meses?"
    ]
    private var blueDes = [
        "*Una respuesta sincera le ayudará a aumentar su límite de crédito",
        "",
        "*Protegeremos y garantizaremos que su información sólo se  utilizará para evaluar su límite de crédito.",
        "",
        ""
    ]
    
    private var options = [
        ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10 veces o más"],
        ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10 transacciones o más"],
        ["0～500peso", "500～1000peso","1000～3000peso", "3000peso o más"],
        ["No", "Sí"],
        ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30 días o más"]
    ]
    var GASQ : Int = 0

    
    private var m4enterTime: Int = 0
    
    let emailTFTag = 101
    var filteredMenuData: [String] = []
    
    lazy var scrollView: UIScrollView = {
        let scroll = UIScrollView()
        scroll.backgroundColor = .white
        scroll.contentSize.width = M4ScreenWidth
        scroll.showsVerticalScrollIndicator = false
        scroll.showsHorizontalScrollIndicator = false
        return scroll
    }()
    
    lazy var tipImageView: M4InfosTopKycTipImageView = {
        let view = UINib(nibName: "M4InfosTopKycTipImageView", bundle: nil).instantiate(withOwner: self).last as! M4InfosTopKycTipImageView
        view.M4TipimageView.image = UIImage(named: "img_schedule0")
        
        view.setStyledCreditText(amountText: "$ 12,000",typestr: 0)
        return view
    }()
    
    lazy var bottomView: M4InfosBottomView = {
        let view = M4InfosBottomView()
        view.m4View.c = self
        view.m4BottomButtonBlock = { button in
            //提交信息
//            let vc = M4SecondInfoViewController()
//            self.navigationController?.pushViewController(vc, animated: true)
//            button.M4EventUnavailable = false
            self.view.endEditing(true)
            self.M4SubmitFirstInfoNet()
        }
        return view
    }()
    
    private var m4inputTFViews: [M4InfosPublicView1] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.GASQ = 1

        m4enterTime = Int(Date().timeIntervalSince1970 * 1000)
        self.view.backgroundColor = .white
        M4NavBarColor = .white
        M4BackIcon = "icon_back_black"
        M4NavTitle(M4Title: "Información credit", M4NavTitleColor: COLOR_333333)
        m4updateUI()
//        M4ItemInfoNet()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.isHidden = false
        
        
        let params: [[String:Any]] = [
            [
                "adga" : 13001,
                "sdqw" : inTime,
                "hgjyj" : Int(Date().timeIntervalSince1970 * 1000) ,
                "GASQ" : GASQ
            ]
        ]
        M4HiddenPointDataManager.M4UploadHiddenPoint(type: .creditInfoZhanQi, paramsKey: "QWkzj", params: params, complete: nil)
    }
    
    override func M4BackClick(sender: UIButton) {
        view.endEditing(true)
        M4InfosPageBack()
        sender.M4EventUnavailable = false
    }
    private func m4updateUI() {
        
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-M4SafeDistanceBottom())
            make.width.equalTo(M4ScreenWidth)
        }
        
        view.addSubview(scrollView)
        scrollView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(M4NavigationFullHeight()+0.5)
            make.left.right.equalToSuperview()
//            make.bottom.equalToSuperview().offset(-M4SafeDistanceBottom())
            make.bottom.equalTo(bottomView.snp.top).offset(-16)
        }
        scrollView.addSubview(tipImageView)
        tipImageView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(15)
            make.left.right.equalToSuperview()
            make.width.equalTo(M4ScreenWidth)
        }
        if M4CreditStatusManager.m4CreditShare.m4isEmailAuth == 1 { //==1
            titles.append("Correo electrónico")
        }
        
        // 先在 scrollView 中加一个垂直 stackView
        let stackView = UIStackView()
        stackView.axis = .vertical
        stackView.spacing = 0
        stackView.alignment = .fill
        stackView.distribution = .fill
        scrollView.addSubview(stackView)
        stackView.translatesAutoresizingMaskIntoConstraints = false

        stackView.snp.makeConstraints { make in
            // 上下左右贴合 contentLayoutGuide
            make.top.equalTo(tipImageView.snp.bottom)
            make.bottom.equalTo(scrollView.contentLayoutGuide)
            make.left.right.equalTo(scrollView.contentLayoutGuide)

            // 宽度和 scrollView 的 frameLayoutGuide 一致
            make.width.equalTo(scrollView.frameLayoutGuide)
        }
//        stackView.snp.makeConstraints { make in
//            make.edges.equalToSuperview()
//            make.width.equalToSuperview()
//        }

        for i in 0..<titles.count {
            let view = UINib(nibName: "M4InfosPublicView1", bundle: nil)
                .instantiate(withOwner: self)
                .last as! M4InfosPublicView1

            view.m4InfoPublicTitle.text = titles[i]
            view.m4InfoPublicTF.isUserInteractionEnabled = false
            view.tag = i
            view.isHidden = (i != 0)
            view.m4InfoPublicBlueDesc.text = blueDes[i]

            m4inputTFViews.append(view)
            stackView.addArrangedSubview(view)

            view.addGestureRecognizer(
                UITapGestureRecognizer(target: self, action: #selector(M4ItemTap(gesture:)))
            )
        }
        
        
        
        
        var temView: M4InfosPublicView1?
//        
//        for i in 0..<titles.count {
//            let view = UINib(nibName: "M4InfosPublicView1", bundle: nil).instantiate(withOwner: self).last as! M4InfosPublicView1
//            view.m4InfoPublicTitle.text = titles[i]
//            view.m4InfoPublicTF.isUserInteractionEnabled = false
//            view.tag = i
//            view.isHidden = i == 0 ? false : true
//            view.m4InfoPublicBlueDesc.text = blueDes[i]
//            m4inputTFViews.append(view)
//            scrollView.addSubview(view)
//            view.snp.makeConstraints { make in
//                make.left.right.equalToSuperview()
//                if temView == nil {
//                    make.top.equalTo(tipImageView.snp.bottom)
//                } else {
//                    make.top.equalTo(temView!.snp.bottom)
//                }
//                
//                make.width.equalTo(M4ScreenWidth)
//                if i == titles.count - 1 {
//                    make.bottom.equalTo(scrollView.snp.bottom).offset(-16).priority(.high)
//                }
//            }
//            view.addGestureRecognizer(UITapGestureRecognizer(target: self,
//                                                             action: #selector(M4ItemTap(gesture:))))
//            
//            temView = view
//        }
    }
}

extension M4CrediteInfoViewController {
    
    @objc private func M4ItemTap(gesture: UITapGestureRecognizer) {
        view.endEditing(true)
        let tag = gesture.view?.tag ?? 0
        M4ItemViewShow(tag: tag)
    }
    
    private func M4AtomicShowInfoView(tag: Int) {
        var m4tag = tag
        if M4CreditStatusManager.m4CreditShare.m4isEmailAuth == 1 { //== 1
            if m4tag == m4inputTFViews.count-2 {
                m4tag = 0
            }
            for i in m4tag..<m4inputTFViews.count-1 {
                if m4inputTFViews[i].m4InfoPublicTF.text?.count == 0 {
                    M4ItemViewShow(tag: i)
                    break
                }
            }
        }
        else {
            if m4tag == m4inputTFViews.count-1 {
                m4tag = 0
            }
            for i in m4tag..<m4inputTFViews.count {
                if m4inputTFViews[i].m4InfoPublicTF.text?.count == 0 {
                    M4ItemViewShow(tag: i)
                    break
                }
            }
        }
    }
    
    private func M4ItemViewShow(tag: Int) {
        var itemData: [M4InfoItemListModel] = []
        let option = options[tag]
        for i in 0..<option.count {
            itemData.append(M4InfoItemListModel(GTG: option[i], IfSps: "\(i)"))
        }
        
        let listView = UINib(nibName: "M4InfosListAlertView", bundle: nil).instantiate(withOwner: self).last as! M4InfosListAlertView
        listView.M4InfosListUpdateUI(title: titles[tag], data: itemData)
        listView.M4SelectedInfoReturn = { chooseString in
            self.m4inputTFViews[tag].m4InfoPublicError.text = ""
            self.m4inputTFViews[tag].m4InfoPublicTF.text = chooseString
//            self.M4AtomicShowInfoView(tag: tag)
            self.changeViewHiddenState()
        }
        if m4inputTFViews[tag].m4InfoPublicTF.text?.count != 0 {
            for k in 0..<listView.M4CellData.count {
                let str = listView.M4CellData[k].GTG
                if str == m4inputTFViews[tag].m4InfoPublicTF.text {
                    listView.M4SelectedIndex = k
                    break
                }
            }
        }
        listView.M4PopViewShow(subview: listView.M4InfosListBGView)
    }
    
    
    func changeViewHiddenState() {
        

            let loanCountText = m4inputTFViews[0].m4InfoPublicTF.text ?? ""

            if loanCountText == "0" || loanCountText.isEmpty {
                for i in 1..<m4inputTFViews.count {
                    m4inputTFViews[i].m4InfoPublicTF.text = ""
                    m4inputTFViews[i].isHidden = true
                   
                }
                return
            } else {
                m4inputTFViews[1].isHidden = false
               
                m4inputTFViews[3].isHidden = false
              
            }

            let inLoanNumberText = m4inputTFViews[1].m4InfoPublicTF.text ?? ""
            if inLoanNumberText == "0" || inLoanNumberText.isEmpty {
                m4inputTFViews[2].m4InfoPublicTF.text = ""
                m4inputTFViews[2].isHidden = true

            } else {
                m4inputTFViews[2].isHidden = false

            }

            let overdueSurveyText = m4inputTFViews[3].m4InfoPublicTF.text ?? ""
            if overdueSurveyText == "No" || overdueSurveyText.isEmpty {
                m4inputTFViews[4].m4InfoPublicTF.text = ""
                m4inputTFViews[4].isHidden = true
               
            } else {
                m4inputTFViews[4].isHidden = false
              
            }

    }
}


extension M4CrediteInfoViewController {
    
//    private func M4ItemInfoNet() {
//        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4creditItemInfo, .post, params: ["LVsoN": "ESP", "WWR": M4UserDataManager.m4UserShare.M4Itemcode])) { model in
//            if model.code == 1 {
//                let data = model.data as? [String : Any]
//                let education = data?["Mfqb"] as? [[String : Any]]
//                let marry = data?["Zchnx"] as? [[String : Any]]
//                let work = data?["GatrBqom"] as? [[String : Any]]
//                let income = data?["UoLvMAykrN"] as? [[String : Any]]
//                let relationship = data?["LtrTCz"] as? [[String : Any]]
//                self.m4educationData = education?.kj.modelArray(M4InfoItemListModel.self) ?? []
//                self.m4marryData = marry?.kj.modelArray(M4InfoItemListModel.self) ?? []
//                self.m4workData = work?.kj.modelArray(M4InfoItemListModel.self) ?? []
//                self.m4incomeData = income?.kj.modelArray(M4InfoItemListModel.self) ?? []
//                self.m4relationshipData = relationship?.kj.modelArray(M4InfoItemListModel.self) ?? []
//                
////                self.M4ItemViewShow(tag: 0)
//            }
//            else {
//                self.view.makeToast(model.message, position: .center)
//            }
//        }
//    }
        
    private func M4SubmitFirstInfoNet() {
        DispatchQueue.main.asyncAfter(wallDeadline: .now()+2) {
            self.bottomView.m4submitButton.M4EventUnavailable = false
        }
        let errors = [
            "Por favor seleccione su experiencia de préstamo",
            "Por favor seleccione el monto de su préstamo",
            "Por favor seleccione el monto impago",
            "Por favor seleccione si hay pedidos pendientes de pago",
            "Por favor seleccione el número de días"
        ]
        
        var r = true
        
        
        for i in 0..<m4inputTFViews.count {
            if m4inputTFViews[i].isHidden == true { break}
            let s = m4inputTFViews[i].m4InfoPublicTF.text ?? ""
            if s.count == 0 {
                m4inputTFViews[i].m4InfoPublicError.text = errors[i]
                r = false
            }
        }
        if r == false { return }
        
        
        let m4submitTime: Int = Int(Date().timeIntervalSince1970 * 1000) - m4enterTime
        var param1: [String : Any] = ["FeqKW": M4UserDataManager.m4UserShare.M4Itemcode, "YOcQCpfM": "ESP", "KKo": M4UserDataManager.m4UserShare.M4ProductCode, "CAdRudKdvHw": M4UserDataManager.m4UserShare.M4Token, "Zucl": 12, "MrAavSrhrC": "0", "GcnkGKIZC": "0", "SHsg": m4submitTime]
        
        let ASD = m4inputTFViews[1].m4InfoPublicTF.text
        let msksk = m4inputTFViews[2].m4InfoPublicTF.text
        let Isksk = m4inputTFViews[3].m4InfoPublicTF.text
        let Nusus = m4inputTFViews[4].m4InfoPublicTF.text
                
        param1["Gss"] = m4inputTFViews[0].m4InfoPublicTF.text ?? "0"
        param1["ASD"] = ASD?.count == 0 ? "0" : ASD
        param1["msksk"] = msksk?.count == 0 ? "0" : msksk
        param1["Isksk"] = Isksk=="Sí" ? 1 : 0
        param1["Nusus"] = Nusus?.count == 0 ? "0" : Nusus
        
        param1["MIsnu"] = inTime
        param1["GGedgh"] = Int(Date().timeIntervalSince1970 * 1000)  - inTime
        
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4submitCreditInfo, .post, params: param1)) { model in
            self.bottomView.m4submitButton.M4EventUnavailable = false
            if model.code == 1 {
                M4HomeViewController.M4InfoController { c in
                    if c != nil {
                        self.navigationController?.pushViewController(c!, animated: true)
                    } else {
                        if self.navigationController?.viewControllers.first is M4CrediteInfoViewController ||
                            self.navigationController?.viewControllers.first is M4FirstInfoViewController {
                            AppDelegate.keyWindow()?.rootViewController = M4TabBarViewController()
                        }
                        else {
                            self.navigationController?.popToRootViewController(animated: true)
                        }
                    }
                }
            }
            else {
                self.view.makeToast(model.message, position: .center)
            }
        }
    }
    
}
